import React, { useContext, useMemo, useRef, useState } from 'react';
import { Button, Space, message, Modal } from 'antd';
import { WorkflowHndTaskBtn } from '@/components/WorkflowCommonCopy';
import { AllBtnsConfig, invalidModalOnOk, renderTipName } from '../mconfig';
import { ConractControllerContext } from '../common';
import { TipsErrorModalNew } from '@/components/TipsErrorModalNew';
import { invalidContractService } from '../services';
import { RollbackOutlined, QuestionCircleOutlined } from '@ant-design/icons';
import moment from 'moment';
import { getTenantID } from '@/utils';
import { ILoadMapTypeAll } from '@/common';
import { history } from 'umi';

export const DetailInfoBottomBtnView = ({ position }) => {
  /** 申请页ref */
  const tipErrorModalRef: any = useRef();

  /** 引入上下文 */
  const { taskId, curRes, pageType, contractDetailInfo, contractForm, oldContractInfo, styleFixCls, reloadDetail, setOAMessageRun, locationState } =
    useContext(ConractControllerContext);

  /** 签发提示框 */
  const [openTipInfoModal, setOpenTipInfoModal] = useState<Record<string, any>>({
    checkRowObj: {},
    showModal: false,
    tipType: null, // delete:删除   revoke:撤销
  });

  /** 按钮是否显示 */
  const allBtnsMemo = useMemo(() => {
    return AllBtnsConfig(curRes, contractDetailInfo, false, contractForm, oldContractInfo, pageType);
  }, [curRes, contractDetailInfo, contractForm, oldContractInfo, pageType]);

  /** 签发按钮关闭 */
  const tipOnClose = () => {
    setOpenTipInfoModal({
      checkRowObj: {},
      showModal: false,
      tipType: null,
    });
  };

  /** 提示弹框回调 */
  const tipModalCallback = (res: any) => {
    if (res && res?.msgFlag) {
      message.success(res?.msg);
      reloadDetail();
      tipOnClose();
    } else {
      message.error(res?.msg);
    }
  };

  /** 引入撤销接口 */
  const { invalidContractRun } = invalidContractService(tipModalCallback);

  const { confirm } = Modal;

  const closeCurrent = () => {
    confirm({
      title: '关闭',
      icon: <QuestionCircleOutlined />,
      content: '确定要关闭当前页吗？',
      okText: '确定',
      okType: 'primary',
      cancelText: '取消',
      onOk() {
        history.push({
          pathname: locationState?.returnPathName || '/contractController/homePage',
          state: {
            delRouterNameSource: history.location.pathname, //必传,要删除的路由名称
            returnPathName: locationState?.returnPathName,
          },
        });
      },
      onCancel() {},
    });
  };

  return (
    <div className={`${styleFixCls}infoViewOA-bottomBtnBox-spaceItemBox`}>
      {allBtnsMemo?.allBtnDiv && (
        <Space>
          {/* 流程节点弹框 */}
          {position == 'top' && (
            <WorkflowHndTaskBtn
              flowDetailInfo={allBtnsMemo?.flowHandList}
              reloadCallback={reloadDetail}
              requestController={'contractController'}
              // handHelpType={false}
              clickSuccessFun={() => {
                setOAMessageRun({
                  id: taskId,
                  isRemark: 2,
                  viewType: 1,
                  endTime: moment()?.format('YYYY-MM-DD HH:mm:ss'),
                });
              }}
              flowBusinessType={`${getTenantID()}${ILoadMapTypeAll.ALLFLOW_TYPE}1007`}
            />
          )}
          {allBtnsMemo?.revokeBtnDiv && position == 'top' && (
            <Button
              type="primary"
              danger
              icon={<RollbackOutlined />}
              onClick={() => {
                setOpenTipInfoModal({
                  checkRowObj: contractDetailInfo,
                  showModal: true,
                  tipType: 'revoke',
                });
              }}
            >
              撤销
            </Button>
          )}
          <Button danger onClick={closeCurrent}>
            关闭
          </Button>
        </Space>
      )}

      {!allBtnsMemo?.allBtnDiv && (
        <div className="tabsBodyBottomBtn">
          <Button danger onClick={closeCurrent}>
            关闭
          </Button>
        </div>
      )}

      {/* 提示框 */}
      {openTipInfoModal?.showModal && (
        <TipsErrorModalNew
          ref={tipErrorModalRef}
          modalLoading={false}
          onClose={tipOnClose}
          modalOnOK={
            openTipInfoModal?.tipType == 'revoke'
              ? () => {
                  invalidModalOnOk(openTipInfoModal?.checkRowObj, invalidContractRun);
                }
              : () => {}
          }
          tipTextColor="#000"
          modalTip={renderTipName(openTipInfoModal?.tipType, openTipInfoModal?.checkRowObj)}
        />
      )}
    </div>
  );
};
